part of _;

extension on ShowVideoPage {
  void controller_showActions() {
    yShowActionSheet("请选择", ["保存视频"], (_, action) async {
      switch (action) {
        case "保存视频":
          if (yIsWeb)
            html.window.open(video, "");
          else {
            yShowProgress();
            GallerySaver.saveVideo(video).then((isSuccess) {
              yDismissProgress();
              yToast((isSuccess ?? false) ? "视频保存成功" : "视频保存失败");
            });
          }
          break;
      }
    });
  }

  void controller_disposeVideo() {
    isPlaying = false;
    try {
      if (listener != null) videoController?.removeListener(listener!);
    } catch (e) {}
    try {
      chewieController?.pause();
    } catch (e) {}
    try {
      videoController?.pause();
    } catch (e) {}
    try {
      videoController?.dispose();
    } catch (e) {}
    try {
      chewieController?.dispose();
    } catch (e) {}
  }

  void controller_initVideo() async {
    String cacheKey() => "video_cache_$video";

    void initVideo() async {
      controller_disposeVideo();
      try {
        setState(() {});
      } catch (e) {}
      listener = () async {
        if (!mounted || !yIsAlive) return;
        if (!isPlaying && chewieController!.isPlaying) {
          yRun(() {
            if (!mounted || !yIsAlive) return;
            try {
              setState(() => isPlaying = true);
            } catch (e) {}
            if (lastPosition != null) {
              chewieController?.seekTo(lastPosition!);
              lastPosition = null;
            }
          }, delay: video.startsWith("http") ? 2000 : 0);
        }
        if (chewieController!.isPlaying) {
          if ((await chewieController!.videoPlayerController.position)! >= chewieController!.videoPlayerController.value.duration) {
            initVideo();
          }
        }
      };
      videoController = video.startsWith("http") ? VideoPlayerController.network(video) : VideoPlayerController.file(File(video));
      chewieController = ChewieController(
        videoPlayerController: videoController!,
        autoInitialize: true,
        autoPlay: true,
        showControls: true,
        showControlsOnInitialize: true,
        looping: false,
        //showControls: !(yIsWeb && defaultTargetPlatform == TargetPlatform.android),
        errorBuilder: (context, errorMessage) => const Center(child: Icon(Icons.error_outline, color: Colors.white, size: 50)),
      );
      videoController!.addListener(listener!);
      try {
        setState(() {});
      } catch (e) {}
    }

    void downloadVideo() async {
      final path = "${await FileUtils.getDir(FileDir.cache_video)}${DateTime.now().microsecondsSinceEpoch}_${FileUtils.getFileName(video)}";
      final cancelToken = CancelToken();
      final response = await Dio().download(
        video,
        path,
        cancelToken: cancelToken,
        deleteOnError: true,
        onReceiveProgress: (count, total) {
          if (total > 100 * 1024 * 1024) {
            // 100MB以上的文件不缓存，此处停止下载
            cancelToken.cancel();
            return;
          }
        },
      );
      if (response.statusCode != 200) return;
      ySave(cacheKey(), path);
      isNet = false;
      video = path;
      lastPosition = await chewieController?.videoPlayerController.position;
      initVideo();
    }

    if (!video.startsWith("http")) {
      // 不是网络视频，直接播放
      isNet = false;
      initVideo();
      return;
    }
    final path = await yRead(cacheKey());
    if (path != null && File(path).existsSync()) {
      // 本地有缓存，使用缓存地址播放
      isNet = false;
      video = path;
      initVideo();
      return;
    }
    initVideo();
    downloadVideo();
  }
}
